package finalproject.mobapp.Main;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import finalproject.mobapp.R;
import finalproject.mobapp.HttpRequestController.CustomHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	public static final String PREF_NAME = "SHARED_PREFERENCES";
	public static SharedPreferences prefs;
	
	/** Called when the activity is first created. */
	
	EditText username;
	EditText password;
	Button login_btn;
	TextView result;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        login_btn = (Button)findViewById(R.id.login_btn);
        result = (TextView)findViewById(R.id.result_text);        
    }
	
	public void loginHandle(View v) {
		String username = LoginActivity.this.username.getText().toString();
		String password = LoginActivity.this.password.getText().toString();
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    	postParameters.add(new BasicNameValuePair("username", username));
    	postParameters.add(new BasicNameValuePair("password", password));
    	
    	String response = null;
    	try {
    		response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "loginMobile", postParameters);
    		String res=response.toString();
     	    res= res.replaceAll("\\s+","");
     	    
     	    if(res.equals("0")) {
     	    	result.setText("Sorry!! Incorrect Username or Password");
     	    }
     	    else {
     	    	int user_id = Integer.parseInt(res);
     	    	
     	    	prefs = this.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
     	    	prefs.edit().putInt("user_id", user_id).commit();
     	    	
     	    	Intent intent = new Intent();
     	    	intent.setClass(this, MenuActivity.class);
     	    	
     	    	LoginActivity.this.finish();
     	    	startActivity(intent);
     	    }
		} catch (Exception e) {
			// TODO: handle exception
			this.username.setText(e.toString());
		}
	}
}
